package com.bestv.search.management.datasyn;

import com.bestv.search.common.dataSource.DataSourceKey;
import com.bestv.search.common.dataSource.DataSourceKeyUtil;
import com.bestv.search.common.model.Info;
import com.bestv.search.common.model.InfoHeader;
import com.bestv.search.common.model.InfoHeaderItem;
import com.bestv.search.common.util.StringConst;

import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Michael Wang
 */

// $Id$
public class VisDbMovieItemSyncer extends ProgramSyncerImpl {

    final static String sDBDriver = "oracle.jdbc.driver.OracleDriver";
    final static String filterFile = "filterWords.properties";
    final static int progValid = 1;

    String orclUrl = null;
    String encoding = "ISO8859_1";
    String user = null;
    String pass = null;
    String movieItemView = null;

    public VisDbMovieItemSyncer(Map<String, String> p) throws Exception {
        this.setProps(p);
        justDoIt();
    }

    @Override
    public boolean init(Map<String, String> properties) {

        // init last sync time
        if (!initLastSyncTime(StringConst.BESTV_VIS, 1, StringConst.VIS_MOVIE_ITEM_SYNC_TIME)) {
            return false;
        }

        // Gets orclUrl
        if (props.get("orclUrl") == null || props.get("orclUrl").length() == 0) {
            logger.error("orclUrl is empty!");
            result = false;
            return false;
        } else {
            orclUrl = props.get("orclUrl");
        }

        // Gets movie view
        if (props.get("movieItem") == null || props.get("movieItem").length() == 0) {
            logger.error("movieItem view is empty!");
            result = false;
            return false;
        } else {
            movieItemView = props.get("movieItem");
        }

        // Gets encoding
        if (props.get("encoding") == null || props.get("encoding").length() == 0) {
            logger.warn("encoding is empty, use ISO8859_1");
        } else {
            encoding = props.get("encoding");
        }

        // Gets user and password
        user = props.get("user");
        pass = props.get("pass");

        return true;
    }

    @Override
    public boolean updateProgram() throws Exception {
        logger.info("Now read from vis db movie item and update to search's");
        thisSyncTime = lastSyncSuccessfullTime;

        Connection conn = null;
        ResultSet rs = null;
        Statement stmt = null;

        String syncMessage = "Success sync movie item from Vis system @ " + new Date();
        try {
            Class.forName(sDBDriver);
            conn = DriverManager.getConnection(orclUrl, user, pass);
            stmt = conn.createStatement();
            rs = stmt.executeQuery("select * from " + movieItemView + " where LAST_UPDATE_TIME >= to_date('"
                    + timeformat.format(lastSyncSuccessfullTime)
                    + "','YYYY-MM-DD HH24:MI:SS') order by LAST_UPDATE_TIME asc");

            logger.info("A new batch begins at movie_item_update_time " + timeformat.format(lastSyncSuccessfullTime));
            DataSourceKey dsKey = DataSourceKeyUtil.convert(systemCache.getLocalDataSourceKey());
            while (rs.next()) {
                Date now = new Date();
                try {
                    Date updateTime = rs.getTimestamp("LAST_UPDATE_TIME");
                    if (thisSyncTime == null || updateTime.after(thisSyncTime)) {
                        thisSyncTime = updateTime;
                    }

                    String code = rs.getString("PROGRAM_CODE");
                    List<Info> infos = vm.getInfoByCode(dsKey, code);
                    if (infos == null || infos.size() == 0) {
                        logger.error(" Info don't found! pcode=" + code);
                    } else {
                        Info infoInDB = null;
                        for (Info info : infos) {
                            if (info.getUpdateFlag() != 2) {
                                infoInDB = info;
                                break;
                            }
                        }
                        if (infoInDB != null) {
                            // Gets HDSDFLAG 1：标清正片, 2： 高清正片, 3:预告片
                            int hdsd = rs.getInt("HDSD_TYPE");
                            // Sets content_flag, 1：正片, 2： 预告片
                            if (hdsd == 3) {
                                infoInDB.setContent_flag(2);
                            } else {
                                infoInDB.setContent_flag(1);
                            }

                            // 电 影版本 1：原声版 2：国语版 3： 粤语版 4：自定义
                            int itemVersion = rs.getInt("ITEM_VERSION");
                            if (itemVersion == 1) {
                                infoInDB.setContent_version(StringConst.ORIGINAL_SOUND_CHINESE);
                            } else if (itemVersion == 2) {
                                infoInDB.setContent_version(StringConst.MANDARIN_SOUND_CHINESE);
                            } else if (itemVersion == 3) {
                                infoInDB.setContent_version(StringConst.CANTONESE_CHINESE);
                            } else {
                                infoInDB.setContent_version(StringConst.CUSTOM_CHINESE);
                            }

                            infoInDB.setUpdateTimeForIndex(now);
                            infoInDB.setUpdateTimeMillis(Long.valueOf(updatetimeformat.format(now)));
                            vm.saveUpdateInfo(dsKey, infoInDB);

                            // Gets info header
                            String movieCode = rs.getString("MOVIE_CODE");
                            InfoHeader header = infoHeaderManager.get(dsKey, movieCode);
                            if (header != null) {
                                int movieOrder = rs.getInt("ITEM_ORDER");

                                InfoHeaderItem infoHeaderItem = new InfoHeaderItem();
                                infoHeaderItem.setInfo_header_id(header.getId());
                                infoHeaderItem.setInfo_id(infoInDB.getId());
                                infoHeaderItem.setInfo_order(movieOrder);
                                infoHeaderItem.setOriginal_info_order(movieOrder);
                                infoHeaderItem.setUpdateTime(now);

                                infoHeaderItemManager.saveOrUpdate(dsKey, infoHeaderItem);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("read movie item error! pcode=" + rs.getString("CODE"));
                }
            }
        } catch (Exception e) {
            System.out.println(e);
            syncMessage = "Failed sync Movie Item from Vis system @ " + new Date();
            result = false;
            throw e;
        } finally {
            if (rs != null)
                rs.close();
            if (stmt != null)
                stmt.close();
            if (conn != null)
                conn.close();

            // Update Sync status.
            updateSyncStatus(StringConst.BESTV_VIS, 1, StringConst.VIS_MOVIE_ITEM_SYNC_TIME, syncMessage, thisSyncTime);
        }

        return true;
    }

    String unifyStr(String s) throws UnsupportedEncodingException {
        if (s == null)
            return null;
        String toCode = encoding.equalsIgnoreCase("iso-8859-1") ? "gbk" : "utf-8";
        return new String(s.getBytes(encoding), toCode).trim();
    }
}